package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;

import javax.annotation.Resource;
import java.util.List;

import static com.itheima.constant.MessageConstant.*;

@Service(version = "1.0")
public class CheckItemServiceImpl implements CheckItemService {
    @Resource
    CheckItemMapper checkItemMapper;

    @Override
    public Result findPage(QueryPageBean queryPageBean) {

        try {
            //分页
            PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

            Page<CheckItem> page = checkItemMapper.findByCondition(queryPageBean.getQueryString());

            PageResult pageResult = new PageResult();
            pageResult.setRows(page.getResult());
            pageResult.setTotal(page.getTotal());
            return Result.success(QUERY_CHECKITEM_SUCCESS, pageResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(QUERY_CHECKITEM_FAIL);
    }

    @Override
    public Result findById(Integer id) {
        try {
            CheckItem checkItem = checkItemMapper.findById(id);
            return Result.success(QUERY_CHECKITEM_SUCCESS, checkItem);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(QUERY_CHECKITEM_FAIL);
    }

    @Override
    public Result save(CheckItem checkItem) {
        try {
            checkItemMapper.save(checkItem);
            return Result.success(ADD_CHECKITEM_SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(ADD_CHECKITEM_FAIL);
    }

    @Override
    public Result update(CheckItem checkItem) {
        try {
            checkItemMapper.update(checkItem);
            return Result.success(EDIT_CHECKITEM_SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(EDIT_CHECKITEM_FAIL);
    }

    @Override
    public Result delete(Integer id) {
        long count = checkItemMapper.count(id);
        if (count > 0) {
            return Result.fail(500, DELETE_CHECKITEM_FAIL);
        }
        checkItemMapper.delete(id);
        return Result.success(DELETE_CHECKITEM_SUCCESS, null);
    }

    @Override
    public Result findAll() {
        try {
            List<CheckItem> all = checkItemMapper.findAll();
            return Result.success(QUERY_CHECKITEM_SUCCESS,all);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(QUERY_CHECKITEM_FAIL);
    }
}
